#!/usr/bin/bash

EPKG_TEST_USER=epkg_test
EPKG_TEST_HOME=$HOME/epkg_test
EPKG_TEST_RESULT=$EPKG_TEST_HOME/result
EPKG_URL=https://repo.oepkgs.net/openeuler/epkg/rootfs/
EPKG_DOWNLOADER_SH=downloader.sh

root_download_user_epkg(){
    $EPKG_TEST_RESULT/$EPKG_DOWNLOADER_SH << EOF
global
y
y
EOF

    if id "$EPKG_TEST_USER" &>/dev/null; then
        echo "User $EPKG_TEST_USER already exists."
    else
        sudo useradd -m "$EPKG_TEST_USER"
        echo "User $EPKG_TEST_USER has been created."
    fi

    sudo -u $EPKG_TEST_USER bash<<EOF
WHICH_TREE_RESULT="/home/epkg_test/.epkg/envs/t1/profile-current/usr/app-bin/tree"
echo "------------------- user switch to \$(whoami) -------------------"
epkg init
source ~/.bashrc
echo "------------------- source \$(whoami) .bashrc -------------------"
epkg create t1
epkg install tree
epkg env list
TREE_PATH=\$(which tree)
if [ "\$TREE_PATH" == "\$WHICH_TREE_RESULT" ]; then
    echo "The tree path is correct: \$TREE_PATH"
else
    echo "The tree path is incorrect. Expected: \$WHICH_TREE_RESULT, but got: \$TREE_PATH"
fi
EOF
}

user_dowload_user_epkg() {
    $EPKG_TEST_RESULT/$EPKG_DOWNLOADER_SH << EOF
user
y
y
EOF

    WHICH_TREE_RESULT="$HOME/.epkg/envs/t1/profile-current/usr/app-bin/tree"
    epkg init
    source ~/.bashrc
    epkg create t1
    epkg install tree
    epkg env list
    TREE_PATH=$(which tree)
    if [ "$TREE_PATH" == "$WHICH_TREE_RESULT" ]; then
        echo "The tree path is correct: $TREE_PATH"
    else
        echo "The tree path is incorrect. Expected: $WHICH_TREE_RESULT, but got: $TREE_PATH"
    fi
}

clear_downloader() {
    # 
    /bin/rm -rf /opt/.epkg/
    /bin/rm -rf /opt/.cache/epkg/
    /bin/rm -rf /opt/.temp/elf-loader
    /bin/rm -rf /opt/.temp/store.tar.gz
    /bin/rm -rf /root/.epkg/
    /bin/rm -rf /home/epkg_test/.epkg/
    # 
    /bin/rm -rf /usr/bin/epkg
    /bin/rm -rf /bin/epkg
    #
    sed -i '/.epkg/d; /EPKG_INITIALIZED=yes/d; /EPKG_INSTALL_MODE=/d' "/root/.bashrc"
    sed -i '/.epkg/d; /EPKG_INITIALIZED=yes/d; /EPKG_INSTALL_MODE=/d' "/home/epkg_test/.bashrc"
}

mkdir -p $EPKG_TEST_RESULT
if [ ! -f "$EPKG_TEST_RESULT/$EPKG_DOWNLOADER_SH" ]; then
    curl -o $EPKG_TEST_RESULT/$EPKG_DOWNLOADER_SH $EPKG_URL/$EPKG_DOWNLOADER_SH
    chmod a+x $EPKG_TEST_RESULT/$EPKG_DOWNLOADER_SH
fi

if [ $USER == root ]; then
    root_download_user_epkg
else
    user_dowload_user_epkg
fi
